package org.Iteracion3.dominio;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.Iteracion3.persistencia.*;

public class GestorBillete {
	Agente agente ;
	/**
	 * 
	 * @param b
	 * @throws Exception 
	 */
	public GestorBillete() throws Exception{
		agente=Agente.getAgente();
	}
	public int insert(Billete b) throws SQLException, Exception {
		// TODO - implement GestorBillete.insert

		ResultSet r=agente.select("SELECT Precio FROM VIAJEBILLETE WHERE (Origen='"+b.getViaje().getOrigen()+"' AND Destino='"+b.getViaje().getDestino()+"');");
		if(r.next()){
			b.setPrecio(r.getDouble("Precio"));
		}
		
		return agente.insert("INSERT INTO BILLETES VALUES ("+b.getId()+","+b.getPrecio()+","+b.getViaje().getId()+",'"+b.getCliente().getDni()+"','"+b.getAsiento()+"');");
	}

	/**
	 * 
	 * @param b
	 */
	public void update(Billete b) {
		// TODO - implement GestorBillete.update
		//throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @param b
	 * @throws Exception 
	 * @throws SQLException 
	 */
	public int delete(Billete b) throws SQLException, Exception {
		// TODO - implement GestorBillete.delete		
		return agente.delete("DELETE FROM BILLETES WHERE (Id="+b.getId()+");");
	}

	/**
	 * 
	 * @param b
	 * @throws Exception 
	 * @throws SQLException 
	 */
	public void read(Billete b) throws SQLException, Exception {
		// TODO - implement GestorBillete.read
		ResultSet r;
		//if(b.getId()!=-1){
		Viaje v;
			r=agente.select("SELECT * FROM BILLETES WHERE Id="+b.getId()+";");
			if(r.next()){
				v=new Viaje(r.getInt("Viaje"),null,null,null,null,null,null);
				v.leerViaje();
				b.setViaje(v);
				b.setCliente(new Cliente(r.getString("Cliente"),null, null));
				b.setAsiento(r.getString("Asiento"));
			}
		//}else{
			r = agente.select("SELECT Precio FROM VIAJEBILLETE WHERE (Origen='"+b.getViaje().getOrigen()+"' AND Destino='"+b.getViaje().getDestino()+"');");
			if(r.next()){
				b.setPrecio(r.getDouble("Precio"));
			}
		//}
	}
	
	public List<Billete> readAll() throws SQLException, Exception {
		// TODO - implement GestorBillete.readAll
		
		List<Billete> b=new ArrayList<Billete>();
		ResultSet r=agente.select("SELECT * FROM BILLETES;");
		Viaje viaje;
		Cliente cliente;
		while(r.next()){
			viaje = new Viaje(r.getInt("Viaje"),null,null,null,null,null,null);
			cliente = new Cliente(null, null, r.getString("Cliente"));
			b.add(new Billete(r.getInt("Id"),r.getDouble("Precio"), viaje, cliente, r.getString("Asiento")));
		}
		return b;
	}

}